package logic

import (
	"context"
	"fmt"
	"zhihu/mobels/cache"
	"zhihu/mobels/mysql"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterOrLoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterOrLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterOrLoginUserLogic {
	return &RegisterOrLoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterOrLoginUserLogic) RegisterOrLoginUser(in *zhihurpc.RegisterOrLoginUserRequest) (*zhihurpc.RegisterOrLoginUserResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+"registerOrLogin"+in.Mobile)

	if get.Val() != in.CodeSms {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	var user mysql.User
	mysql.DB.Where("mobile = ?", in.Mobile).Find(&user)

	if user.ID == 0 {
		user = mysql.User{
			Mobile: in.Mobile,
		}
		err := mysql.DB.Debug().Create(&user).Error
		if err != nil {
			fmt.Errorf("注册异常")
		}
	}

	//登录成功后删除短信验证码缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"registerOrLogin"+in.Mobile)
	return &zhihurpc.RegisterOrLoginUserResponse{UserId: int64(user.ID)}, nil
}
